package org.oexam.ostudy.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.oexam.ostudy.struct.UserTypes;
import org.oexam.ostudy.struct.Users;

public class DBConnection {
	
	private static Connection conn;

	public Connection getConnection() throws SQLException, NamingException {

		if(conn==null){
		Context initCtx = new InitialContext();

		Context envCtx = (Context) initCtx.lookup("java:comp/env");

		DataSource ds = (DataSource) envCtx.lookup("jdbc/OESS_DB");

		conn = ds.getConnection();

		Statement s = conn.createStatement();

		s.executeQuery("USE OESS_DB");
		
		} 
		return conn;

	}

	public ResultSet executeQuery(String query) throws SQLException,
			NamingException {

		
		// Test code Start.
		
		Users users = new Users();
		users.setUser_id(1);
		users.setUser_name("aaa");
		users.setPassword("pass");
		users.setUser_type(11);
		
		UserTypes utype = new UserTypes();
		utype.setuType_id(11);
		utype.setUser_type("dads");
		
		SessionFactory sf = new Configuration().configure().buildSessionFactory();


		Session session = sf.openSession();

		session.beginTransaction();
		
		//session.save(utype);
		//session.save(users);
		
		
		session.getTransaction().commit();
		session.close();
		// Test code end.
		Connection conn = new DBConnection().getConnection();

		Statement s = conn.createStatement();

		ResultSet resultSet = null;
		try {
			resultSet = s.executeQuery(query);

		} catch (SQLException e) {
			throw e;
		} finally {
//			if (s != null) {
//				s.close();
//			}
		}
        
		
		return resultSet;

	}
	
	public void executeUpdate(String query) throws SQLException,
	NamingException {


Connection conn = new DBConnection().getConnection();

Statement s = conn.createStatement();


try {
	s.executeUpdate(query);

} catch (SQLException e) {
	throw e;
} finally {

}



}
	
	// This is a test method to test Hibernate.
	public void initializeDB(){
		/*
		Announcements h = new Announcements(1,"This is a test headline.", new Date());
		Announcements h1 = new Announcements(2,"Exams postponed.", new Date());


		SessionFactory sf = new Configuration().configure().buildSessionFactory();


		Session session = sf.openSession();

		session.beginTransaction();

		session.save(h);
		session.save(h1);
session.get(Announcements.class, 1);

		session.getTransaction().commit();
		session.close();
		*/
		
	}

}
